<script setup>
import { getClassify } from '@/api/commodity'
import { ref, onMounted, toRefs } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
})

const { modelValue } = toRefs(props);
const classifyId = ref([])
const emit = defineEmits(['update:modelValue']);

// 初始化查询所有分类
let categoryList = ref([]);
function queryAllCategory () {
  getClassify().then(res => {
    categoryList.value = res.data
    handleRemoveEmptyChild(categoryList.value)
  })
}
function handleRemoveEmptyChild (arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].childs) {
      if (Array.isArray(arr[i].childs) &&
          arr[i].childs.length === 0) {
        delete arr[i].childs
      } else {
        handleRemoveEmptyChild(arr[i].childs)
      }
    }
  }
}

function cascaderChane (val) {
  console.log(val, 'val')
  const classifyId = Array.isArray(val)
    ? val[val.length - 1]
    : val
  emit('update:modelValue', classifyId)
}

onMounted(() => {
  queryAllCategory()
})
</script>

<template>
  <el-cascader
    v-model="classifyId"
    :options="categoryList"
    clearable
    :props="{
      checkStrictly: true,
      expandTrigger: 'hover',
      label: 'categoryName',
      value: 'id',
      children: 'childs',
    }"
    @change="cascaderChane"
  />
</template>

<style scoped lang="scss">

</style>